const express = require('express')
const app = express()
const jwt = require('jsonwebtoken')
// token所需密钥
const SECRET = 'lcp'

app.use(require('cors')())
app.use(express.json({limit: '50mb'}))

const mongoose = require('mongoose')
const Schema = mongoose.Schema
mongoose.connect('mongodb://localhost:27017/fruit',{
    useNewUrlParser:true,
    useUnifiedTopology:true,
    useCreateIndex:true,
    useFindAndModify:false 
})

// 用户模型
const UserSchema = new mongoose.Schema({
    username:{type:String,unique:true},
    // 密码加密
    password:{type:String,set(val){
        return require('bcryptjs').hashSync(val,10)
    }},
    role_name:{type:String},
    mobile:{type:String},
    email:{type:String},
    mg_state:{type:Boolean}
})
const UserModel = mongoose.model('User',UserSchema)

// 添加用户
// UserModel.create({
//     username:"ghh",
//     password:'123456',
//     role_name: "超级管理员",
//     mobile: "13888888880",
//     email: "123456@qq.comm",
//     mg_state: false
// })

// 1.登录
app.post('/api/login',async(req,res)=>{
    const user = await UserModel.findOne({
        username:req.body.username
    })
    // 用户名验证
    if(user.mg_state === false){
        return res.send({message:'用户名被禁用',status:420})
    }
    if(!user){
        return res.send({message:'用户名不存在',status:421})
    }
    // 密码验证
    const isPasswordValid = require('bcryptjs').compareSync(req.body.password,user.password)
    if(!isPasswordValid){
        return res.send({message:'密码错误',status:422})
    }
    // 登录成功
    // 生成token
    const token = jwt.sign({
        id:String(user._id),
    },SECRET)
    res.send({message:'登录成功！',status:200,token:token})
})

// 2.菜单列表

// 菜单模型
const MenuSchema = new mongoose.Schema({
    id:{type:String,unique:true},
    authName:{type:String},
    path:{type:String},
    children:{type:Object}
})
const MenuModel = mongoose.model('menus',MenuSchema)
// 添加菜单项
// MenuModel.create({
//     id:101,
//     authName:"商品管理",
//     path:"goods",
//     children:[] 
// })
app.get('/api/menus',async(req,res)=>{
    const menus = await MenuModel.find({},{_id:0}).sort({id:1})
    res.send(menus)
})

// 3.用户列表
app.get('/api/users',async(req,res)=>{
    let reg = new RegExp(req.query.query,'i')
    let size = Number(req.query.pagesize)
    let pageNum = Number(req.query.pagenum)
    const user = await UserModel.find({
        $or:[
            {username:{$regex:reg}},
            {role_name:{$regex:reg}},
            {mobile:{$regex:reg}},
            {email:{$regex:reg}},
        ]
    })
    let result = await UserModel.find({
        $or:[
            {username:{$regex:reg}},
            {role_name:{$regex:reg}},
            {mobile:{$regex:reg}},
            {email:{$regex:reg}},
        ]
    }).skip((pageNum-1)*size).limit(size)
    res.send({
        users:result,
        total:user.length,
        pagenum:Number(pageNum)
    })
})

// 4.更新用户状态
app.put('/api/users/:uId/state/:type',async(req,res)=>{
    const user = await UserModel.findByIdAndUpdate(req.params.uId,
    {
        mg_state:req.params.type
    })
    res.send(user)
})


// 5.添加用户
app.post('/api/users',async(req,res)=>{
    const user = await UserModel.create({
            username:req.body.username,
            password:req.body.password,
            role_name: "超级管理员",
            mobile: req.body.mobile,
            email: req.body.email,
            mg_state: false
    })
    res.send({msg:'添加用户成功！'})
})

// 6.根据ID查询用户信息
app.get('/api/users/:id',async(req,res)=>{
    const user = await UserModel.findOne({_id:req.params.id})
    res.send(user)
})

// 7.编辑用户提交
app.put('/api/users/:id',async(req,res)=>{
    await UserModel.findByIdAndUpdate(req.params.id,req.body)
    res.send({msg:'修改成功！'})
})

// 8.删除用户
app.delete('/api/users/:id',async(req,res)=>{
    await UserModel.findByIdAndDelete(req.params.id)
    res.send({msg:'删除成功！'})
})

// 商品分类模型
const CateSchema = new mongoose.Schema({
    // cat_id: {type:Number,unique:true},
    cat_name: {type:String},
    cat_pid: {type:Number},
    cat_level: {type:Number},
    cat_state: {type:Boolean},
    // children:[
    //     {
    //         cat_id: {type:Number,unique:true},
    //         cat_name: {type:String},
    //         cat_pid: {type:Number},
    //         cat_level: {type:Number},
    //         cat_state: {type:Boolean},
    //     }
    // ]
})
const CateModel = mongoose.model('categories',CateSchema)

// CateModel.create({
//     cat_id: 1905,
//     cat_name: "火龙果",
//     cat_pid: 0,
//     cat_level: 0,
//     cat_state: false, 
// })

// 9.获取商品分类数据
app.get('/api/categories',async(req,res)=>{
    let pagesize = Number(req.query.pagesize)
    let pagenum = Number(req.query.pagenum)
    const cate = await CateModel.find()
    const cateT = await CateModel.find({cat_state:true})
    let result = await CateModel.find()
    .skip((pagenum-1)*pagesize).limit(pagesize)
    
    if(req.query.type === '3'){
        res.send({
            result:result,
            total:cate.length,
            pagesize:Number(pagesize),
            pagenum:Number(pagenum)
        })
    }else{
        res.send(cateT)
    }
})

// 10.添加商品分类
app.post('/api/categories',async (req,res)=>{
    // console.log(req)
    //  body: { cat_name: '233', cat_pid: 0, cat_level: 0 },
    const num = await CateModel.find()
    // console.log(num.length)
    if(req.body.cat_level === 0){
        const cate = await CateModel.create({
            cat_id: (req.body.cat_level+1)*1000+num.length+1,
            cat_name: req.body.cat_name,
            cat_pid: req.body.cat_pid,
            cat_level: req.body.cat_level,
            cat_state: true,
        })
        return res.send({err:0,msg:'添加成功',cate:cate})
    }else{
        const cate = await CateModel.findOneAndUpdate({cat_id:req.body.cat_pid},{$push:{
            children:{
                cat_id: (req.body.cat_level+1)*1000+num.length,
                cat_name: req.body.cat_name,
                cat_pid: req.body.cat_pid,
                cat_level: req.body.cat_level,
                cat_state: false,
            }
        }})
        return res.send({err:0,msg:'添加成功',cate:cate})
    }
})

// 11.更新用户状态
app.put('/api/categories/:uId/state/:type',async(req,res)=>{
    const cate = await CateModel.findByIdAndUpdate(req.params.uId,
    {
        cat_state:req.params.type
    })
    res.send(cate)
})

// 12.根据ID查询商品分类信息
app.get('/api/categories/:id',async(req,res)=>{
    const cate = await CateModel.findOne({_id:req.params.id})
    res.send(cate)
})

// 13.编辑商品分类提交
app.put('/api/categories/:id',async(req,res)=>{
    await CateModel.findByIdAndUpdate(req.params.id,req.body)
    res.send({msg:'修改成功！'})
})

// 14.删除商品分类
app.delete('/api/categories/:id',async(req,res)=>{
    await CateModel.findByIdAndDelete(req.params.id)
    res.send({msg:'删除成功！'})
})


// 商品模型 
const GoodSchema = new mongoose.Schema({
    // goods_id: {type:Number,unique:true},
    // cat_id: {type:Number,default:null},
    cat_name:{type:String},
    goods_name: {type:String},
    goods_price: {type:Number},
    goods_number: {type:Number},
    goods_weight: {type:Number},
    goods_introduce:{type:String},
    goods_cat:{type:String},
    pics:{type:Array},
    goods_state: Schema.Types.Mixed,
    goods_collect:{type:Boolean,default:false},
    add_time: {type:Number,default:new Date().getTime()}, 
    upd_time: {type:Number},
    hot_mumber: {type:Number},
    is_promote: {type:Boolean},
    cat_one_id: Schema.Types.Mixed,
    cat_two_id: Schema.Types.Mixed,
    cat_three_id: Schema.Types.Mixed
})
const GoodModel = mongoose.model('goods',GoodSchema)

// GoodModel.create({
//     goods_id: 4,
//     cat_id: null,
//     goods_name: "苹果",
//     goods_price: 87,
//     goods_number: 9498,
// })
 
// 15.商品列表
app.get('/api/goods',async(req,res)=>{
    let reg = new RegExp(req.query.query,'i')
    let size = Number(req.query.pagesize)
    let pageNum = Number(req.query.pagenum)
    const good = await GoodModel.find({
        $or:[
            {goods_name:{$regex:reg}},
        ]
    })
    let result = await GoodModel.find({
        $or:[
            {goods_name:{$regex:reg}},
        ]
    }).skip((pageNum-1)*size).limit(size)
    res.send({
        goods:result,
        total:good.length,
        pagenum:Number(pageNum)
    })
})

// 16.删除商品
app.delete('/api/goods/:id',async(req,res)=>{
    await GoodModel.findByIdAndDelete(req.params.id)
    res.send({msg:'删除成功！'})
})

// 17.添加商品
app.post('/api/goods',async(req,res)=>{
    // console.log(req.body.goods_cat)
    const goodName = await CateModel.findOne({_id:req.body.goods_cat})
    const good = await GoodModel.create({
        cat_name:goodName.cat_name,
        goods_cat:req.body.goods_cat,
        goods_introduce:req.body.goods_introduce,
        goods_name:req.body.goods_name,
        goods_number:req.body.goods_number,
        goods_price:req.body.goods_price,
        pics:req.body.pics
    })
    res.send({msg:'添加成功',good:good})
})

// 18.根据ID查询商品信息
app.get('/api/goods/:id',async(req,res)=>{
    const good = await GoodModel.findOne({_id:req.params.id})
    res.send(good)
})

// 19.编辑商品提交
app.put('/api/goods/:id',async(req,res)=>{
    console.log(req.body) 
    const goodName = await CateModel.findOne({_id:req.body.goods_cat})
    const good = await GoodModel.findByIdAndUpdate(req.params.id,{
        goods_name:req.body.goods_name,
        goods_price:req.body.goods_price,
        goods_number:req.body.goods_number,
        goods_cat:req.body.goods_cat[0],
        cat_name:goodName.cat_name,
    })
    res.send({msg:'修改成功！'})
})





// 小程序接口
// 1.分类侧边栏
app.get('/api/wechat/categories',async(req,res)=>{
    const cate = await CateModel.find({cat_state:true}).find({cat_name:{$ne:'首页'}})
    res.send({cate:cate})
})

// 2.分类商品列表
app.get('/api/wechat/categorieslist',async(req,res)=>{
    // console.log(req.query)
    const list = await GoodModel.find({goods_cat:req.query.id})
    res.send({list:list})
})

// 3.修改商品收藏
app.put('/api/wechat/goods/:id',async(req,res)=>{
    // console.log(req.body) 
    const good = await GoodModel.findByIdAndUpdate(req.params.id,{
        goods_collect:req.body.goods_collect,
    })
    res.send({msg:'修改成功！'})
})

app.listen(3001,()=>{
    console.log('正在监听3001端口')
})